package io.bhex.app.account.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import java.util.List;

import io.bhex.app.R;
import io.bhex.app.account.presenter.KycLevelVideoPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.hardware.CameraHardWare;
import io.bhex.app.hardware.CameraPreview;
import io.bhex.app.hardware.MediaPlayerSurfaceView;
import io.bhex.app.utils.NumberUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.bean.UserVerifyInfo;
import io.bhex.sdk.account.bean.kyc.KycLevelBean;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * ================================================
 * 作   者：ppzhao
 * 创建时间：2019-11-14
 * 邮   箱：
 * 描   述：KYC 视频录制认证
 * ================================================
 */

public class KycLevelVideoActivity extends BaseActivity<KycLevelVideoPresenter, KycLevelVideoPresenter.KycLevelVideoUI> implements KycLevelVideoPresenter.KycLevelVideoUI, View.OnClickListener, EasyPermissions.PermissionCallbacks, MediaPlayer.OnCompletionListener {

    private static final int MEDIA_RECORDER_REQUEST_CODE = 0x1;
    private static final int MAX_DURATION_SECOND = 60;
    private static final long MAX_DURATION_RECORD = MAX_DURATION_SECOND * 1000;
    private CameraPreview msPreview;
    private boolean isRecording;
    private Camera mCamera;
    private CameraPreview mPreview;
    private String[] perms = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
    private CountDownTimer countDownTimer;
    private ProgressBar progressTime;
    private CountDownTimer countDownTimerProgress;
    private FrameLayout preview;
    private MediaPlayerSurfaceView surface;
    private boolean isFull;
    private KycLevelBean threeLevel;

    @Override
    protected int getContentView() {
        return R.layout.activity_kyc_level_video_layout;
    }

    @Override
    protected KycLevelVideoPresenter createPresenter() {
        return new KycLevelVideoPresenter();
    }

    @Override
    protected KycLevelVideoPresenter.KycLevelVideoUI getUI() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        countDownTimer = new CountDownTimer(MAX_DURATION_RECORD, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                viewFinder.textView(R.id.durationTime).setText(millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {

            }
        };

        countDownTimerProgress = new CountDownTimer(MAX_DURATION_RECORD, 100) {

            @Override
            public void onTick(long millisUntilFinished) {
                int percent = (int) (NumberUtils.div(MAX_DURATION_RECORD, millisUntilFinished) * 100);
                progressTime.setProgress(percent);
            }

            @Override
            public void onFinish() {

            }
        };

    }

    @Override
    protected void initView() {
        super.initView();
        Intent intent = getIntent();
        if (intent != null) {
            threeLevel = (KycLevelBean) intent.getSerializableExtra("levelBean");
        }
        progressTime = viewFinder.find(R.id.pb);
        preview = (FrameLayout) findViewById(R.id.camera_preview);
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), MEDIA_RECORDER_REQUEST_CODE, perms);
        } else {
            createCameraPreview();
        }
//        if (!CameraHardWare.getInstance(this).checkCameraHardware(this)) {
//            //TODO
//        }

        //MediaPlayer surface
        surface = viewFinder.find(R.id.surface);
        if (threeLevel != null) {
            String videoAgreement = threeLevel.getVideoAgreement();
            if (!TextUtils.isEmpty(videoAgreement)) {
                viewFinder.textView(R.id.kyc_tips).setVisibility(View.VISIBLE);
                viewFinder.textView(R.id.kyc_tips).setText(videoAgreement);
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    public void showVerifyInfo(UserVerifyInfo response) {
//        if (response != null) {
//            viewFinder.textView(R.id.kyc_tips).setVisibility(View.VISIBLE);
//            viewFinder.textView(R.id.kyc_tips).setText(getString(R.string.string_kyc_video_ensure, response.getFirstName() + response.getSecondName(), response.getCardNo()));
//        }
    }

    private void createCameraPreview() {
        // 创建预览视图，并作为Activity的内容
        mCamera = CameraHardWare.getInstance(this).getCameraInstance();
        mPreview = new CameraPreview(this, mCamera);
        preview.addView(mPreview);
    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.button_capture).setOnClickListener(this);
        viewFinder.find(R.id.btnClose).setOnClickListener(this);
        viewFinder.find(R.id.btnNext).setOnClickListener(this);
        viewFinder.find(R.id.btnPlay).setOnClickListener(this);
        viewFinder.find(R.id.btnResetRecord).setOnClickListener(this);
        viewFinder.find(R.id.btnSubmit).setOnClickListener(this);

        surface.setOnVideoPlayingListener(new MediaPlayerSurfaceView.OnVideoPlayingListener() {
            @Override
            public void onVideoSizeChanged(int vWidth, int vHeight) {

            }

            @Override
            public void onPlaying(int duration, int percent) {

            }

            @Override
            public void onStart() {

            }

            @Override
            public void onPlayOver() {
                setPlayBtnShow(true);
            }

            @Override
            public void onVideoSize(int videoSize) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnClose:
                this.finish();
                break;
            case R.id.btnNext:
//                IntentUtils.goMediaPlayer(this);
                break;
            case R.id.button_capture:
                if (isRecording) {
                    stopMediaRecorder();
                } else {
                    startMediaRecorder();
                }
                break;
            case R.id.btnPlay:
                playVideo();
                break;
            case R.id.btnResetRecord:
                //重新录制 TODO
                showMediaPlayer(false);
                stopPlayer();
                startMediaRecorder();
                break;
            case R.id.btnSubmit:
                //提交审核 TODO
                getPresenter().uploadFile(CameraHardWare.getInstance(this).getVideoFile());
                break;
        }
    }

    private void startMediaRecorder() {
        // initialize video camera

        boolean isPrepareVideoRecorder = CameraHardWare.getInstance(this).prepareVideoRecorder(mCamera, mPreview, MAX_DURATION_RECORD, new MediaRecorder.OnInfoListener() {
            @Override
            public void onInfo(MediaRecorder mr, int what, int extra) {
                if (what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED) {
                    ToastUtils.showShort(getString(R.string.string_video_record_max_time,MAX_DURATION_SECOND));
                    stopMediaRecorder();
                }
            }
        });
        if (isPrepareVideoRecorder) {
            // Camera is available and unlocked, MediaRecorder is prepared,
            // now you can start recording
            CameraHardWare.getInstance(this).startMediaRecorder();
            // inform the user that recording has started
            setCaptureButtonStatus(R.mipmap.btn_record_stop);
            countDownTimer.start();
            countDownTimerProgress.start();
            isRecording = true;
        } else {
            // prepare didn't work, release the camera
            CameraHardWare.getInstance(this).releaseMediaRecorder();
            // inform user
        }
    }

    private void stopMediaRecorder() {
        // stop recording and release camera
        CameraHardWare.getInstance(this).stopMediaRecorder();
        CameraHardWare.getInstance(this).releaseMediaRecorder(); // release the MediaRecorder object
        CameraHardWare.getInstance(this).lockCamera();
        countDownTimer.cancel();
        countDownTimerProgress.cancel();
        // inform the user that recording has stopped
        setCaptureButtonStatus(R.mipmap.btn_record_start);
        viewFinder.textView(R.id.durationTime).setText(getString(R.string.string_kyc_level_three));
        isRecording = false;
        notifyPlayVideo(CameraHardWare.getInstance(this).getVideoFile());
    }

    private void setCaptureButtonStatus(int intRes) {
        viewFinder.imageView(R.id.button_capture).setImageResource(intRes);
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopMediaRecorder();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopMediaRecorder();
        if (surface != null) {
            surface.finishVideo();
            // Activity销毁时停止播放，释放资源。不做这个操作，即使退出还是能听到视频播放的声音
        }
    }

    /**
     * 通知播放视频
     *
     * @param videoFile
     */
    private void notifyPlayVideo(String videoFile) {
        if (!TextUtils.isEmpty(videoFile)) {
            showMediaPlayer(true);
            setPlayerDataSource(videoFile);
        }
    }

    private void showMediaPlayer(boolean isShow) {
        viewFinder.find(R.id.mediaPlayerRela).setVisibility(isShow?View.VISIBLE:View.GONE);
        viewFinder.find(R.id.videoPreView).setVisibility(isShow?View.VISIBLE:View.GONE);
        viewFinder.find(R.id.surface).setVisibility(isShow?View.VISIBLE:View.GONE);
        setPlayBtnShow(isShow);
        viewFinder.find(R.id.recorderRela).setVisibility(!isShow?View.VISIBLE:View.GONE);
        viewFinder.find(R.id.camera_preview).setVisibility(!isShow?View.VISIBLE:View.GONE);
    }

    private void setPlayerDataSource(String videoFile) {
        // 设置显示视频显示在SurfaceView上
        surface.setUrl(videoFile);
        viewFinder.imageView(R.id.videoPreView).setVisibility(View.VISIBLE);
        viewFinder.imageView(R.id.videoPreView).setImageBitmap(getVideoThumb(videoFile));
    }

    private void playVideo() {
        // 设置显示视频显示在SurfaceView上
        setPlayBtnShow(false);
       surface.play();
    }

    private void stopPlayer(){
        try{
            if (surface != null) {
                surface.stop();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //全屏切换
    public void isFull(){
        if (isFull){
            surface.setHalfScreen();
            isFull=false;
        }else {
            surface.setFullScreen();
            isFull=true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        finish();
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == MEDIA_RECORDER_REQUEST_CODE) {
            //TODO 授权成功：
            createCameraPreview();
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        setPlayBtnShow(false);
    }

    private void setPlayBtnShow(boolean isShow) {
        viewFinder.find(R.id.btnPlay).setVisibility(isShow ? View.VISIBLE : View.GONE);
        viewFinder.imageView(R.id.videoPreView).setVisibility(isShow? View.VISIBLE : View.GONE);
    }

    public Bitmap getVideoThumb(String path){
        MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
        mediaMetadataRetriever.setDataSource(path);
        return mediaMetadataRetriever.getFrameAtTime();
    }
}
